using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using VOL.Entity.DomainModels;
using SqlSugar;

namespace VOL.demo.Repositories
{
    public partial class productinformationmodelRepository
    {
        /// <summary>
        /// 获取货品信息下拉选项
        /// </summary>
        /// <param name="keyword">搜索关键词</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="pageSize">每页记录数</param>
        /// <returns>货品信息列表</returns>
        public async Task<(List<productinformationmodel> Data, int TotalCount)> GetProductOptionsAsync(
            string keyword = null,
            int pageIndex = 1,
            int pageSize = 10)
        {
            // 构建基础查询
            var baseQuery = DbContext.Queryable<productinformationmodel>()
                .LeftJoin<producttypemodel>((p, pt) => p.productTypeId == pt.id)
                .LeftJoin<unitmodel>((p, pt, u) => p.UnitId == u.Id)
                .Where((p, pt, u) => p.IsDel == 0);

            // 添加关键词搜索条件
            if (!string.IsNullOrEmpty(keyword))
            {
                baseQuery = baseQuery.Where((p, pt, u) => p.goodsCode.Contains(keyword) || p.goodsName.Contains(keyword));
            }

            // 执行 Select 投影
            var query = baseQuery
                .Select((p, pt, u) => new productinformationmodel
                {
                    Id = p.Id,
                    goodsCode = p.goodsCode,
                    goodsName = p.goodsName,
                    status = p.status,
                    productTypeId = p.productTypeId,
                    specModel = p.specModel,
                    supplierId = p.supplierId,
                    userId = p.userId,
                    purchasePrice = p.purchasePrice,
                    salePrice = p.salePrice,
                    displayOrder = p.displayOrder,
                    currentInventory = p.currentInventory,
                    totalInventoryamount = p.totalInventoryamount,
                    shelfLifeManagement = p.shelfLifeManagement,
                    shelfLife = p.shelfLife,
                    shelfLifeUnit = p.shelfLifeUnit,
                    warningDays = p.warningDays,
                    notes = p.notes,
                    IsDel = p.IsDel,
                    Creator = p.Creator,
                    CreateDate = p.CreateDate,
                    Modifier = p.Modifier,
                    ModifyDate = p.ModifyDate,
                    CreateID = p.CreateID,
                    ModifyID = p.ModifyID,
                    UnitId = p.UnitId,  // 保留原始UnitId值，不从关联表获取
                    // 添加typeName字段
                    typeName = pt.typeName,
                    // 添加UnitName字段
                    UnitName = u.UnitName
                })
                .OrderBy(p => p.goodsName);

            var totalCount = await query.CountAsync();
            var data = await query.ToPageListAsync(pageIndex, pageSize);

            return (data, totalCount);
        }

        /// <summary>
        /// 根据货品ID获取货品信息
        /// </summary>
        /// <param name="productId">货品ID</param>
        /// <returns>货品信息</returns>
        public async Task<productinformationmodel> GetProductByIdAsync(long productId)
        {
            return await DbContext.Queryable<productinformationmodel>()
                .Where(x => x.Id == productId && x.IsDel == 0)
                .FirstAsync();
        }

        /// <summary>
        /// 根据货品ID列表批量获取货品信息
        /// </summary>
        /// <param name="productIds">货品ID列表</param>
        /// <returns>货品信息列表</returns>
        public async Task<List<productinformationmodel>> GetProductsByIdsAsync(List<long> productIds)
        {
            if (productIds == null || productIds.Count == 0)
            {
                return new List<productinformationmodel>();
            }

            return await DbContext.Queryable<productinformationmodel>()
                .Where(x => productIds.Contains(x.Id) && x.IsDel == 0)
                .ToListAsync();
        }

        /// <summary>
        /// 添加新产品
        /// </summary>
        /// <param name="product">产品信息</param>
        /// <returns>成功返回true，失败返回false</returns>
        public async Task<bool> AddProductAsync(productinformationmodel product)
        {
            if (product == null)
            {
                return false;
            }

            try
            {
                // 设置创建时间
                product.CreateDate = DateTime.Now;
                
                // 插入数据
                var result = await DbContext.Insertable(product).ExecuteCommandAsync();
                return result > 0;
            }
            catch (Exception)
            {
                return false;
            }
        }

        /// <summary>
        /// 检查产品编号是否已存在
        /// </summary>
        /// <param name="goodsCode">产品编号</param>
        /// <returns>存在返回true，不存在返回false</returns>
        public async Task<bool> IsProductCodeExistsAsync(string goodsCode)
        {
            if (string.IsNullOrEmpty(goodsCode))
            {
                return false;
            }

            var count = await DbContext.Queryable<productinformationmodel>()
                .Where(x => x.goodsCode == goodsCode && x.IsDel == 0)
                .CountAsync();

            return count > 0;
        }
    }
}